using Furion.DatabaseAccessor;

using Microsoft.EntityFrameworkCore;

using System.Collections.Generic;
using System.Threading.Tasks;

using Tool;

namespace Abc.Application
{
    /// <summary>
    /// 赠删改查父类
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <typeparam name="TDbContextLocator"></typeparam>
    public abstract class QueryService<TEntity, TDbContextLocator>
        where TEntity : class, IPrivateEntity, new()
        where TDbContextLocator : class, IDbContextLocator
    {
        public string CacheKey { get; set; }

        /// <summary>
        /// 注入仓储
        /// </summary>
        private readonly IRepository<TEntity, TDbContextLocator> _repository;

        /// <summary>
        /// 构造函数
        /// </summary>
        public QueryService(string cachekey)
        {
            this.CacheKey = cachekey;
            _repository = Db.GetRepository<TEntity, TDbContextLocator>();
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<TEntity>> GetEntities()
        {
            var entities = await MemoryCacheExtension.GetMemoryCacheAsync<List<TEntity>>(CacheKey);
            if (entities.Count <= 0)
            {
                entities = await RefreshMemberCache();
            }
            return entities;
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<TEntity>> RefreshMemberCache()
        {
            var entities = await _repository.DetachedEntities.ToListAsync();
            entities.SetMemoryCache(CacheKey);
            return entities;
        }
    }
}